﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PMP.Data;
using PMP.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace PMP.Controllers
{
    public class AdminController : Controller
    {
        private readonly PMPContext _context;
        public AdminController(PMPContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> DailyList()
        {
            var dailyList = await _context.Daily.ToListAsync();
            return View(dailyList);
        }


        public IActionResult DailyAdd()
        {
            return View();
        }

        public async Task<IActionResult> Daily_Save(Daily daily)
        {
            if (daily.ID == 0)
            {
                if (!DateTime.TryParse(daily.Date, out DateTime dateTime))
                {
                    return Json(new { success = false, msg = "日期格式异常" });
                }
                if (await _context.Daily.AnyAsync(x => x.Date == daily.Date))
                {
                    return Json(new { success = false, msg = "日期已存在" });
                }
                var entityEntry = await _context.Daily.AddAsync(daily);
                await _context.SaveChangesAsync();
                var entity = entityEntry.Entity;
                if (entity.ID > 0)
                {
                    return Ok(new { success = true, msg = "添加成功", data = entity });
                }
                return Json(new { success = false, msg = "添加失败" });
            }
            return Json(new { success = false, msg = "操作失败" });
        }


        public async Task<IActionResult> QuestionList(int ID)
        {
            var daily = await _context.Daily.Where(x => x.ID == ID).FirstOrDefaultAsync();
            if (daily == null)
            {
                daily = new Daily() { ID = 0, Date = DateTime.Now.ToString("yyyy-MM-dd") };
            }
            //var list = await _context.Question.Where(x => x.DID == daily.ID).OrderBy(x => x.Order).ToListAsync();
            var list = await _context.Question.Where(x => x.DID == daily.ID).OrderBy(x => x.Order).ToListAsync();
            foreach (var quest in list)
            {
                quest.Options = await _context.Option.Where(x => x.QID == quest.ID).OrderBy(x => x.Order).ToListAsync();
            }
            ViewBag.daily = daily;
            ViewBag.list = list;
            return View();
        }
        public IActionResult All_Save(TempViewData data)
        {
            try
            {

                var tran = _context.Database.BeginTransaction();
                //校验daily数据
                if (!DateTime.TryParse(data.daily.Date, out DateTime dateTime))
                {
                    return Json(new { success = false, msg = "日期格式异常" });
                }
                if (data.daily.ID > 0)
                {
                    if (_context.Daily.Any(x => x.ID != data.daily.ID && x.Date == data.daily.Date))
                    {
                        return Json(new { success = false, msg = "日期已存在" });
                    }
                    _context.Daily.Update(data.daily);
                }
                else
                {
                    if (_context.Daily.Any(x => x.Date == data.daily.Date))
                    {
                        return Json(new { success = false, msg = "日期已存在" });
                    }
                    _context.Daily.Add(data.daily);
                }
                _context.SaveChanges();
                //await _context.SaveChanges();
                Daily daily = _context.Entry(data.daily).Entity;
                foreach (var quest in data.questions)
                {
                    //关联daily
                    quest.DID = daily.ID;
                    //检查question数据
                    if (string.IsNullOrEmpty(quest.Title))
                    {
                        return Json(new { success = false, msg = "题目不能为空" });
                    }
                    quest.Title = quest.Title.Trim();
                    if (string.IsNullOrEmpty(quest.Analysis))
                    {
                        return Json(new { success = false, msg = "解析不能为空" });
                    }
                    quest.Analysis = quest.Analysis.Trim();
                    if (string.IsNullOrEmpty(quest.Mark))
                    {
                        return Json(new { success = false, msg = "知识点不能为空" });
                    }
                    quest.Mark = quest.Mark.Trim();
                    if (quest.ID > 0)
                    {
                        _context.Question.Update(quest);
                    }
                    else
                    {
                        _context.Question.Add(quest);
                    }
                    _context.SaveChanges();
                    Question question = _context.Entry(quest).Entity;
                    //检查option数据
                    if (quest.Options.Count(x => x.IsAnswer) != 1)
                    {
                        return Json(new { success = false, msg = "请设置一个唯一的答案" });
                    }
                    foreach (var option in question.Options)
                    {
                        //关联question
                        option.QID = question.ID;
                        if (string.IsNullOrEmpty(option.Txt))
                        {
                            return Json(new { success = false, msg = "选项不能为空" });
                        }
                        option.Txt = option.Txt.Trim();
                        if (option.ID > 0)
                        {
                            _context.Option.Update(option);
                        }
                        else
                        {
                            _context.Option.Add(option);
                        }
                        _context.SaveChanges();
                    }
                }
                tran.Commit();
                return Json(new { success = true, msg = "已保存" });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, msg = "发生异常", ex = ex.Message });
            }
        }

        public class TempViewData
        {
            public Daily daily { get; set; }
            public List<Question> questions { get; set; }

            public List<Option> options { get; set; }
        }
    }
}
